﻿#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;

using zijian666.Abstractions;
using zijian666.Convertor.Base;
using zijian666.Core;

namespace zijian666.Json.standard20;
public class JsonElementConvertor : AllowNullConvertor<JsonElement>
                                  , IFrom<JsonDocument, JsonElement>
                                  , IFrom<string, JsonElement>
                                  , IFrom<object, JsonElement>
{
    private static readonly JsonDocumentOptions OPTIONS = new JsonDocumentOptions
    {
        AllowTrailingCommas = true,
        CommentHandling = JsonCommentHandling.Skip
    };
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public ConvertResult<JsonElement> From(IConvertContext context, string input)
    {
        return JsonDocument.Parse(input, OPTIONS).RootElement;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public ConvertResult<JsonElement> From(IConvertContext context, JsonDocument input)
    {
        return input.RootElement;
    }

    public ConvertResult<JsonElement> From(IConvertContext context, object input)
    {
#if NET6_0_OR_GREATER
        var element = JsonSerializer.SerializeToElement(input, JsonStringSerializer.SERIALIZE_OPTIONS);
        return element;
#else
        var json = JsonSerializer.Serialize(input);
        return From(context, json);
#endif
    }
}
#endif